﻿Write-Host "功能：将当前目录下的所有文件（文件名格式：全局序号_组内序号），按组别序列化重命名（目标格式：组别序号_组内序号）"

# 让用户输入起始组别号，若没输入默认为 1
$start_group = Read-Host "请输入起始组别号（默认1）"
if ([string]::IsNullOrWhiteSpace($start_group)) {
    $start_group = 1
}

# 检查输入是否为有效数字
if (-not ($start_group -as [int])) {
    Write-Host "输入错误，请输入有效的数字！"
    Read-Host "按 Enter 键关闭"
    exit
}

# 记录开始时间
$startTime = Get-Date

# 初始化变量
$group_num = [int]$start_group - 1
$total_groups = 0
$inner_seq = 0
$prev_inner_seq = 0
$first_file = $true

# 获取当前脚本文件名，防止重命名自身
$scriptFile = [System.IO.Path]::GetFileName($PSCommandPath)

# 全部文件重命名为临时名称（防止重命名过程中文件名冲突）
Get-ChildItem -File | Where-Object { $_.Name -ne $scriptFile -and $_.Name -notlike "__tmp_*" } | ForEach-Object {
    $tmpName = "__tmp_$($_.Name)"
    Rename-Item -Path $_.FullName -NewName $tmpName
}

# 再重命名为最终目标名称
Get-ChildItem -File | Sort-Object Name | Where-Object { $_.Name -like "__tmp_*" } | ForEach-Object {
    #去掉临时前缀
    $origName = $_.Name.Substring(6)

    $fileName = [System.IO.Path]::GetFileNameWithoutExtension($origName)
    $extension = [System.IO.Path]::GetExtension($origName)

    if ($fileName -match "^[^_]+_(\d+)$") {
        $current_inner_seq = [int]$matches[1]

        # 判断是否新组
        if ($first_file) {
            $group_num++
            $total_groups++
            $inner_seq = 0
            $first_file = $false
            Write-Host "正在处理组别：$group_num"
        }
        elseif ($current_inner_seq -lt $prev_inner_seq) {
            $group_num++
            $total_groups++
            $inner_seq = 0
            Write-Host "正在处理组别：$group_num"
        }

        # 保存当前组内序号
        $prev_inner_seq = $current_inner_seq

        # 组内序号递增
        $inner_seq++

        # 生成新文件名（格式：三位组号_三位组内序号）
        $new_group = "{0:D3}" -f $group_num
        $new_inner_seq = "{0:D3}" -f $inner_seq
        $new_name = "$new_group" + "_" + "$new_inner_seq" + $extension

        # 避免重命名死循环
        if ($_.Name -ne $new_name) {
            Rename-Item -Path $_.FullName -NewName $new_name
        }
    }
}

# 记录结束时间并计算耗时（秒）
$endTime = Get-Date
$elapsed = ($endTime - $startTime).TotalSeconds

# 输出结果
Write-Host "处理完成，总计处理组别数：$total_groups（耗时 $([math]::Round($elapsed, 3)) 秒）"
Read-Host "按 Enter 键关闭"